import requests
import time
import datetime
import os
import json
import uuid
from pyquery import PyQuery as pq

# 超清壁纸
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
    "Connection": "keep-alive",
    "Accept": "text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.8"
         }
question = "266772222"
url = 'https://www.zhihu.com/api/v4/questions/'+question+'/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&' \
      'offset=0&platform=desktop&sort_by=default'
def start(offset):
    url = "https://www.zhihu.com/api/v4/questions/"+question+"/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%2Cis_recognized%2Cpaid_info%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&offset=" \
          + str(offset) + "&platform=desktop&sort_by=default"
    res = requests.get(url, headers=headers).text
    data = json.loads(res)
    picRepo = 'E://图片//'+question+'//'
    if not os.path.exists(picRepo):
        os.makedirs(picRepo)
    if data.get("data"):
        for i, item in enumerate(data['data']):
            content = pq(item['content'])
            imgUrls = content.find('noscript img').items()
            for imgTag in imgUrls:
                src = imgTag.attr("src")
                src = str(src).replace("_hd.",".")
                strIndex = src.rfind('.')
                suffix = src[strIndex:]
                uid = str(uuid.uuid4()).replace("-","")
                with open(f"{picRepo}/{uid}{suffix}", 'wb+') as f:
                    f.write(requests.get(src, headers=headers).content)
                    f.close()
def answer(url_):
    r = requests.get(url_, headers=headers)
    data = r.text
    jsonobj = json.loads(data)
    return jsonobj

if __name__ == '__main__':
    starttime = datetime.datetime.now()
    strTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    stime = print(f'开始抓取,当前时间: {strTime}')
    answer_total = int(answer(url)['paging']['totals'])

    offset = 0
    print(answer_total)
    while offset < answer_total:
        start(offset)  # updated:按时间降序，default：默认排序
        offset += 5
        time.sleep(3)
    endtime = datetime.datetime.now()
    print(f'抓取完毕,用时 {((endtime - starttime).seconds)} 秒:')